package org.surelink.radius.middleware.acct;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.surelink.radius.cache.OnlineCache;
import org.surelink.radius.cache.UserCache;
import org.surelink.radius.middleware.AcctMiddleware;
import org.surelink.radius.model.Online;
import org.surelink.radius.model.User;
import org.surelink.radius.utils.DateTimeUtil;
import org.tinyradius.packet.AccountingRequest;

/**
 * 记账上线包处理
 */
public class AcctStartMiddleware implements AcctMiddleware
{

    private static final Logger logger = Logger.getLogger(AcctStartMiddleware.class);

    private static final Logger acctlog = Logger.getLogger("acct");

    @Autowired
    private OnlineCache onlineCache;

    @Autowired
    private UserCache userCache;

    @Override
    public void onAcct(User user, AccountingRequest request) throws Exception {

        if(request.getAcctStatusType()!=AccountingRequest.ACCT_STATUS_TYPE_START)
            return;

        String client = request.getAttributeValue("NAS-IP-Address");
        Online online = onlineCache.get(client, request.getAttributeValue("Acct-Session-Id"));
        if (online != null) {
            if (logger.isInfoEnabled())
                logger.info(String.format("用户[%s]记账请求重复",user.getUserName()));
            return;
        }

        if (user == null) {
            if (logger.isInfoEnabled())
                logger.info(String.format("记账用户[%s]不存在",user.getUserName()));

            return;
        }

        online = new Online();
        online.setAcctStart(DateTimeUtil.getDateTimeString());
        online.setClientAddress(client);
        online.setIpAddress(request.getAttributeValue("Framed-IP-Address"));
        online.setMacAddress(request.getAttributeValue("Calling-Station-Id"));
        online.setNasPort(request.getAttributeValue("NAS-Port"));
        online.setSessionId(request.getAttributeValue("Acct-Session-Id"));
        online.setUserName(user.getUserName());
        online.setStartSource(AccountingRequest.ACCT_STATUS_TYPE_START);
        onlineCache.set(online);

        if (logger.isInfoEnabled())
            logger.info(String.format("用户[%s]记账开始，新增在线用户",user.getUserName()));

    }
}
